<template>
  <div id="app11">
    <d3graph
      :data="data"
      :names="names"
      :labels="labels"
      :linkTypes="linkTypes"
    />
  </div>
</template>

<script>
import d3graph from './d3graph.vue'

export default {
  props: {
    processId: {
      type: Number,
      default: -1
    },
    name: {
      type: String,
      default: 'name'
    },
    nodes: {
      type: Array,
      default: () => {
        return []
      }
    }
  },
  components: {
    d3graph
  },
  mounted() {
    //this.d3jsonParser(require('../data/records.json'))
    this.d3jsonParser(this.getEmissionRecommend());
    // this.getEmissionRecommend()
  },
  watch: {
    temData: {
      deep: true,
      handler(newVal) {
        this.update(this.temData)
      }
    }
  },
  data() {
    return {
      // d3jsonParser()处理 json 后返回的结果
      data: {
        nodes: [],
        links: []
      },
      temData: {},
      names: ['企业', '贸易类型', '地区', '国家'],
      labels: ['Region', 'Country', 'case', 'word'],
      linkTypes: ['', 'type', 'locate', 'export']
    }
  },
  // mounted(){},
  methods: {
    // 推荐排放源
    getEmissionRecommend() {

      var li = []
      var tem = [
        {
          start: {},
          end: {},
          segments: []
        },
      ]
      var response = {
        'process_id': ["20", "20", "20", "20", "20"],
        'emission': [
          {
            "note": "None",
            "emissionsUnitD": "t",
            "matchType": "排放因子",
            "name": "焦炭",
            "id": "25",
            "factor": "焦炭",
            "factorEmissions": "0.54",
            "type": "能源",
            "dataSource": "None",
            "emissionsUnitN": "t CO2-eq"
          },
          {
            "note": "None",
            "emissionsUnitD": "t",
            "matchType": "排放因子",
            "name": "石灰",
            "id": "21",
            "factorEmissions": "1.11",
            "factor": "石灰",
            "type": "资源",
            "dataSource": "None",
            "emissionsUnitN": "t CO2-eq"
          },
          {
            "note": "None",
            "emissionsUnitD": "t",
            "matchType": "排放因子",
            "name": "石膏",
            "id": "33",
            "type": "资源",
            "factorEmissions": "0.2",
            "factor": "石膏粉-工业副产物",
            "dataSource": "None",
            "emissionsUnitN": "t CO2-eq"
          },
          {
            "note": "None",
            "emissionsUnitD": "Nm3",
            "matchType": "排放因子",
            "name": "天然气",
            "id": "34",
            "factorEmissions": "0.64",
            "type": "能源",
            "factor": "天然气",
            "dataSource": "None",
            "emissionsUnitN": "kg CO2-eq"
          },
          {
            "note": "None",
            "emissionsUnitD": "t",
            "matchType": "排放因子",
            "name": "废水",
            "id": "29",
            "factor": "工业废水处置平均",
            "type": "废水",
            "factorEmissions": "15.32",
            "dataSource": "None",
            "emissionsUnitN": "kg CO2-eq"
          }
        ],
        'score': [0.37093253968253964, 0.3557239057239057, 0.3305555555555555, 0.3305555555555555, 0.32015392015392014],
        'rank': [1, 2, 3, 4, 5]
      }
      var data = response.emission
      var score = response.score
      for (var i = 0; i < data.length; i++) {

        console.log(data[i])
        tem[0].segments.push({
          start: {
            identity: data[i].id,
            labels: ['Country'],
            properties: {
              name: data[i].name,
              score: parseFloat(score[i]).toFixed(2)
            }
          },
          end: {
            identity: 10086,
            labels: ['word'],
            properties: {
              name: this.name
            }
          },
          relationship: {
            end: 10086,
            identity: data[i].id,
            properties: {
              name: '推荐'
            },
            start: data[i].id,
            type: "type"
          }
        })
      }
      for (var i = 0; i < this.nodes.length; i++) {
        tem[0].segments.push({
          start: {
            identity: 10086 + i,
            labels: ['word'],
            properties: {
              name: this.nodes[i],
            }
          },
          end: {
            identity: 10086,
            labels: ['word'],
            properties: {
              name: this.name
            }
          },
          relationship: {
            end: 10086,
            identity: 10086 + i,
            properties: {
              name: ''
            },
            start: 10086 + i,
            type: "type"
          }
        })
      }

      // 添加其他的模拟节点
      var mockData = []
      var mockParticle = [
        {
          name: '炼铁',
          nameId: 30000,
          nameStart: 3000,
          nameList: ['矿石', '焦炭', '粉尘', '废水', '废渣']
        },
        {
          name: '炼钢',
          nameId: 40000,
          nameStart: 4000,
          nameList: ['生铁', '废钢', '粉合金元素', '石灰石', '废渣']
        },
        {
          name: '铸造',
          nameId: 50000,
          nameStart: 5000,
          nameList: ['液态钢', '铸模材料', '涂料', '熔剂', '废渣']
        },
        {
          name: '轧制',
          nameId: 60000,
          nameStart: 6000,
          nameList: ['冷轧钢板', '钢坯', '轧辊冷却液', '润滑剂', '废气']
        },
        {
          name: '钢管生产',
          nameId: 70000,
          nameStart: 7000,
          nameList: ['钢板', '加热炉燃料', '冷却水', '固体废弃物', '穿孔模具']
        },
        {
          name: '焊接',
          nameId: 80000,
          nameStart: 8000,
          nameList: ['焊丝', '电极', '冷却水', '保护气体', '通气设备']
        }
      ]
      for (var i = 0; i < mockParticle.length; i++) {
        for (var j = 0; j < mockParticle[i].nameList.length; j++) {
          mockData.push({
            start: {
              identity: mockParticle[i].nameStart + j,
              labels: ['Region'],
              properties: {
                name: mockParticle[i].nameList[j],
                score: 0
              }
            },
            end: {
              identity: mockParticle[i].nameId,
              labels: ['Region'],
              properties: {
                name: mockParticle[i].name
              }
            },
            relationship: {
              end: mockParticle[i].nameId,
              identity: mockParticle[i].nameStart + j,
              start: mockParticle[i].nameStart + j,
              properties: {
                name: '排放源'
              },
              type: "type"
            }
          })

        }
      }
      for (var i = 0; i < mockData.length; i++) {
        tem[0].segments.push(mockData[i])
      }
      this.temData = tem
      for (var i = 0; i < response.length; i++) {
        li.push(response[i]);
      }

      // return li
      // var li = []
      this.$API.product.getEmissionRecommend({
        id: this.processId,
      }).then(response => {
        // var tem = [
        // {
        //   start:{
        //   },
        //   end:{
        //   },
        //   segments:[
        //   ]
        // },
        // ]

        var data = response.data.emission['0']
        var score = response.data.score['0']
        // 推荐的节点
        console.log(data)
        console.log(data.length)
        for (var i = 0; i < data.length; i++) {

          console.log(data[i])
          tem[0].segments.push({
            start: {
              identity: data[i].id,
              labels: ['Country'],
              properties: {
                name: data[i].name,
                score: parseFloat(score[i]).toFixed(2)
              }
            },
            end: {
              identity: 10086,
              labels: ['word'],
              properties: {
                name: this.name
              }
            },
            relationship: {
              end: 10086,
              identity: data[i].id,
              properties: {
                name: '推荐'
              },
              start: data[i].id,
              type: "type"
            }
          })
        }
        console.log(tem[0].segments)
        for (var i = 0; i < this.nodes.length; i++) {
          tem[0].segments.push({
            start: {
              identity: 10086 + i,
              labels: ['word'],
              properties: {
                name: this.nodes[i],
              }
            },
            end: {
              identity: 10086,
              labels: ['word'],
              properties: {
                name: this.name
              }
            },
            relationship: {
              end: 10086,
              identity: 10086 + i,
              properties: {
                name: ''
              },
              start: 10086 + i,
              type: "type"
            }
          })
        }
        this.temData = tem
        for (var i = 0; i < response.length; i++) {
          li.push(response[i]);
        }
      })
      return li
    },
    // 获得排放源-工序关联
    getEmissionAndProcess() {
      this.$API.product.getEmissionAndProcess({
        id: this.processId
      }).then(response => {
        var data = response.data.emissions
        for (var i = 0; i < data.length; i++) {

        }
      })
    },
    // 视图更新
    update(json) {
      this.d3jsonParser(json)
    },
    /*eslint-disable*/
    // 解析json数据，主要负责数据的去重、标准化
    d3jsonParser(json) {
      const nodes = []
      const links = [] // 存放节点和关系
      const nodeSet = [] // 存放去重后nodes的id
      for (let item of json) {
        for (let segment of item.segments) {

          // 重新更改data格式
          if (nodeSet.indexOf(segment.start.identity) == -1) {
            nodeSet.push(segment.start.identity)
            nodes.push({
              id: segment.start.identity,
              label: segment.start.labels[0],
              properties: segment.start.properties
            })
          }
          if (nodeSet.indexOf(segment.end.identity) == -1) {
            nodeSet.push(segment.end.identity)
            //console.log("nodeSet: " + JSON.stringify(segment.start.properties) + "id:" + segment.end.identity)
            nodes.push({
              id: segment.end.identity,
              label: segment.end.labels[0],
              properties: segment.end.properties
            })
          }
          links.push({
            source: segment.relationship.start,
            target: segment.relationship.end,
            type: segment.relationship.type,
            properties: segment.relationship.properties
          })

        }
      }
      // console.log("nodeSet:" + JSON.stringify(nodeSet))
      // console.log("nodeSet Length: " + nodeSet.length);
      // console.log("nodes")
      // console.log(nodes)
      // console.log("links")
      // console.log(links)
      this.data = {nodes, links}
    }
  }
}
</script>

<style lang="scss" scoped>
body {
  margin: 0;
  list-style: none;
  text-decoration: none;
  font-size: 100%;
}

#app11 {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
}

.gContainer {
  position: relative;
  // border: 2px #000 solid;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

#nav {

  // margin-top:30px;
  // position: absolute;
  // top:20px;

  a {
    font-weight: bold;
    color: #2c3e50;

    &.router-link-exact-active {
      color: #42b983;
    }
  }
}
</style>
